import {
  useCallback,
  useEffect,
  useState,
  useMemo,
  ReactElement,
  forwardRef,
  useImperativeHandle,
  ForwardedRef,
  useRef
} from 'react';
import { message, Tabs } from 'antd';
import { SortableContainer, SortableElement, SortableHandle } from 'react-sortable-hoc';
import { arrayMoveImmutable } from 'array-move';
import { getPlatform, InbizIcon } from '@inbiz/utils';
import { TextWidget, getMessage } from '@inbiz/react';
import { EditOutlined, HolderOutlined } from '@ant-design/icons';
import ConfigDetail, { IConfig, IConfigRef, } from './configDetail';
import { crateFileAndfolderLibrary } from './utils'
import { IIndexData } from '../service';
const { TabPane } = Tabs;

export const getDefaultConfig = (title?: string) => {
  return [
    {
      title,
      defaultSearchCriteria: '*',
      sortField: [
        {
          sort: 'desc',
          enable: true,
          IndexFieldDesc: 'SearchResultEngine.matchingDegree',
          IndexFieldName: '',
          default: true,
        },
      ],
    },
  ] as IConfig[];
};

export type ILibraryItem = IIndexData & {
  selected?: boolean;
  configs?: IConfig[];
};

type ILibraryConfig = {
  appId: string;
  value: ILibraryItem[];
  onChange: React.Dispatch<React.SetStateAction<ILibraryItem[]>>;
  changeAddLibraryMode: (visible: boolean) => void;
};

const DragHandle = SortableHandle(() => <HolderOutlined />) as unknown as () => ReactElement;
const SortableItem = SortableElement(
  ({
    value,
    onClick,
  }: {
    value: ILibraryConfig['value'][number];
    index: number;
    onClick: (IndexName: string) => void;
  }) => {
    return (
      <li onClick={() => onClick(value.IndexName)} className={value.selected ? 'selected' : ''}>
        <span
          className="item-content"
          title={
            value.IndexType === -1
              ? getMessage('SearchResultEngine.' + value.IndexName)
              : value.IndexName
          }
        >
          {value.IndexType === -1 ? (
            <TextWidget>{'SearchResultEngine.' + value.IndexName}</TextWidget>
          ) : (
            value.IndexName
          )}
        </span>
        <DragHandle />
      </li>
    );
  },
);

const SortableList = SortableContainer(
  ({ list, onClick }: { onClick: (IndexName: string) => void; list: IIndexData[] }) => {
    return (
      <ul className="scrollbarHover">
        {list.map((value, index) => (
          //@ts-ignore
          <SortableItem
            key={`item-${value.IndexName}`}
            onClick={onClick}
            index={index}
            value={value}
          />
        ))}
      </ul>
    );
  },
);

export type ILibraryRef = {
  getValue: () => Promise<ILibraryItem[]>;
};
function LibraryConfig(props: ILibraryConfig, ref: ForwardedRef<ILibraryRef>) {
  const [list, $list] = useState<ILibraryConfig['value']>([]);
  useEffect(() => {
    $list([...props.value]);
  }, [props.value]);
  const handleSortEnd = useCallback(
    ({ oldIndex, newIndex }: { oldIndex: number; newIndex: number }) => {
      $list((list) => arrayMoveImmutable(list, oldIndex, newIndex));
    },
    [list],
  );
  // 获取最新的配置
  const getConfig = useCallback(
    (selectedKey?: string) => {
      const configs = configRefs.map((item) => item.current.getValue());
      const index = list.findIndex((item) => item.selected);
      const newList = [...list];
      newList[index] = {
        ...newList[index],
        configs,
      };
      if (selectedKey) {
        return newList.map((item) => ({ ...item, selected: item.IndexName === selectedKey }));
      } else {
        return newList;
      }
    },
    [list],
  );
  // 切换索引库
  const handleClick = useCallback(
    (IndexName: string) => {
      const curIndex = list.findIndex((item) => item.selected);
      if (list[curIndex]?.IndexName === IndexName) {
        return;
      }
      // 切换索引库时，保存配置
      props.onChange(getConfig(IndexName));
    },
    [list],
  );
  // 获取最新的value
  useImperativeHandle(
    ref,
    () => ({
      getValue: () => {
        const configList = getConfig();
        const index = configList.findIndex(
          (item) => item.IndexType !== -1 && !item.configs?.[0].title,
        );
        // if (index != -1) {
        const newList = configList.map((item, indexItem) => {
          return {
            ...item,
            selected: indexItem == index,
          };
        });
        $list(newList);
        // message.error(getMessage('SearchResultEngine.titleCannotBeEmpty'));
        // return Promise.reject({ error: 'title不能为空' });
        // }

        return Promise.resolve(configList);
      },
    }),
    [list],
  );
  const configs = useMemo(() => {
    const { configs, selected, ...other } = list.find((item) => item.selected) || {};
    if (!selected) {
      return selected;
    }
    return (configs || [{}]).map((item) => ({ ...other, ...item })) as IConfig[];
  }, [list]);
  const configRefs = useMemo(() => {
    return configs ? configs.map(() => ({ current: null as unknown as IConfigRef })) : [];
  }, [configs]);
  // 创建内置索引库
  const handleCreateLibrary = useCallback(() => {
    const isDocument = list.filter((item) => item.IndexName == 'file' || item.IndexName == 'folder');

    if (isDocument.length == 2) {
      message.error(getMessage('SearchResultEngine.documentIndexLibraryAlreadyExists'));
    } else {
      // 传入错误的选择key， 全部不选中
      const newlist = getConfig('__document');
      // 选中添加的内置选项
      const initData = crateFileAndfolderLibrary()
      const isFile = newlist.some(item => item.IndexName == 'file')
      const isFolder = newlist.some(item => item.IndexName == 'folder')
      if (!isFile && !isFolder) {
        newlist.push(...initData);
      } else if (isFile && !isFolder) {
        newlist.push(initData[1]);
      } else if (!isFile && isFolder) {
        newlist.push(initData[0]);
      }
      newlist[0].selected = true
      $list(newlist);
    }
  }, [list]);
  // 拖动排序挂载节点
  const $ul = useRef(null);

  // 点击添加索引库
  const handleAddLibraryMode = useCallback(() => {
    props.onChange(getConfig());
    props.changeAddLibraryMode(true);
  }, [list, props.changeAddLibraryMode]);

  return (
    <div className="libraryConfig">
      <div className="left">
        <div className="configList">
          <div>
            <span
              className="title"
              title={getMessage('SearchResultEngine.settings.x-component-props.indexIibraryConfig')}
            >
              <TextWidget>
                SearchResultEngine.settings.x-component-props.indexIibraryConfig
              </TextWidget>
            </span>
            <p className="configList-box">
              <InbizIcon
                type="icon-chushihua-suoyinkupeizhi"
                onClick={handleCreateLibrary}
                title={getMessage('SearchResultEngine.initDocumentIndexLibrary')}
              />
              <EditOutlined onClick={handleAddLibraryMode} />
            </p>
          </div>
          {
            //@ts-ignore
            <SortableList
              ref={$ul}
              list={list}
              onSortEnd={handleSortEnd}
              onClick={handleClick}
              useDragHandle
              helperContainer={() => $ul.current?.container || document.body}
            />
          }
        </div>
      </div>
      <div className="right scrollbarHover">
        {configs && <ConfigDetail config={configs[0]} appId={props.appId} ref={configRefs[0]} />}
        {/* (configs[0].tabTitle ? (
        <Tabs defaultActiveKey="0">
              {configs.map((item, index) => {
                return (
                  // <TabPane tab={item.tabTitle} key={index} forceRender>
                    <ConfigDetail config={item} appId={props.appId} ref={configRefs[index]} />
                  // </TabPane>
                );
              })}
            </Tabs>
          ) : (
            
          ))} */}
      </div>
    </div>
  );
}

export default forwardRef(LibraryConfig);
